const request = require('axios')
const puppeteer = require('puppeteer');
const cheerio = require('cheerio');
const fs = require("fs");
const uuid = require("uuid");

module.exports = class Haowallpaper {
    root_url = 'https://haowallpaper.com/'
    typeObj = {
        '电脑壁纸': 'homeView',
        '手机壁纸': 'mobileView'
    }

    constructor() {
    }

    async getPageData_(page) {
        return new Promise(async (resolve, reject) => {
            try {
                await page.waitForSelector('.img-box');
                const lis = await page.$$('.img-box');
                await page.click('.img-box')
                let arr = []
                for (let k of lis) {
                    await k.click()
                    await page.waitForSelector('canvas');
                    // 获取 <canvas> 的图像数据
                    const imageBuffer = await page.evaluate(async () => {
                        let canvas = document.querySelector('canvas')
                        return canvas.toDataURL('image/png')
                    });
                    arr.push(imageBuffer)
                }
                resolve(arr)
            } catch (e) {
                console.log(e)
                reject(e)
            }
        })

    }

    async getAllData(models) {
        let url = 'https://bz.zzzmh.cn/index'
        let p = 1
        let sure_page = 21
        const total_page = 1733
        const {photo_album_item} = models
        const browser = await puppeteer.launch({
            args: ['--disable-web-security', '--no-sandbox'],
            headless: false,   // 设置为 false，浏览器将会显示出来，默认为 true (无头模式)
            slowMo: 50,        // 每个操作之间添加延迟，单位是毫秒
        });
        const page = await browser.newPage();
        await page.goto(url, {waitUntil: 'networkidle2'});  // 等待页面加载完成
        for (let i = p; i <= total_page; i++) {
            if (i !== sure_page) {
                await page.waitForSelector('.vue_pagination_next');
                await page.click('.vue_pagination_next');
            }else{
                let arr = []
                if (i === 1) {
                    arr = await this.getPageData_(page)
                } else {
                    await page.click('.vue_pagination_next');
                    arr = await this.getPageData_(page)
                }
                for (let item of arr) {
                    await photo_album_item.findOrCreate({
                        where: {
                            base64: item,
                        },
                        defaults: {
                            base64: item
                        }
                    })
                }
                console.log(`第${i}页已爬取完成--------------`)
            }

        }
    }

    async getPageData(url) {
        try {
            const t = this
            const browser = await puppeteer.launch();
            const page = await browser.newPage();
            await page.goto(url, {waitUntil: 'networkidle2'});  // 等待页面加载完成
            const content = await page.content();  // 获取完整页面的 HTML 内容
            const $ = cheerio.load(content);
            const li = $('.homeContainer .card')
            let list = []
            li.each((index, element) => {
                const a = $(element).find('.card--button a')
                let href = t.root_url + a.attr('href')
                let title = $(element).find('img').attr('alt')
                href = href.replaceAll('//', '/')
                list.push({
                    title,
                    href
                })
            });
            for (let it of list) {
                this.getImgData(it.href)
            }
        } catch (e) {
            console.log(e.message)
        }

    }

    async downloadImage(url, savePath) {
        try {
            // 发起 GET 请求，获取图片数据
            const response = await request({
                method: 'get',
                url: url,
                responseType: 'stream', // 设置响应类型为 stream
            });

            // 创建一个写入流，将图片数据保存到本地
            const writer = fs.createWriteStream(savePath);

            // 将图片数据通过管道传输到文件中
            response.data.pipe(writer);

            // 等待图片下载完成
            writer.on('finish', () => {
                console.log(`图片已保存到 ${savePath}`);
            });

            // 监听错误
            writer.on('error', (err) => {
                console.error('保存图片时出错:', err);
            });
        } catch (error) {
            console.error('下载图片时出错:', error);
        }
    }

    async getImgData(url) {
        console.log(url, 'url')
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(url, {waitUntil: 'networkidle2'});  // 等待页面加载完成
        const content = await page.content();  // 获取完整页面的 HTML 内容
        // const $ = cheerio.load(content);
        // let total_page = $('#pagination span').find('.isDefault').last().text()
        const $ = cheerio.load(content);
        const src = $('#imgLoad').attr('src')
        const name = $('#imgLoad').attr('alt')
        const filename = uuid.v4().replaceAll('-', '') + '.png'
        const dir = `imgs/${filename}`
        await this.downloadImage(src, dir)
        let item = {
            name,
            down_url: url,
            filename,
            dir,
        }
        let data = fs.readFileSync('./imgs.json', 'utf-8')
        console.log(data)
        data = data ? JSON.parse(data) : []
        let flag = data.find(el => el.down_url === url)
        if (!flag) {
            data.push(item)
            fs.writeFileSync('./imgs.json', JSON.stringify(data), 'utf-8')
        }

    }

    async getHomePageData() {
        try {
            let type = '电脑壁纸'
            // const browser = await puppeteer.launch({headless: false});
            // const page = await browser.newPage();
            // await page.goto(this.root_url, {waitUntil: 'networkidle2'});  // 等待页面加载完成
            // const content = await page.content();  // 获取完整页面的 HTML 内容
            // const $ = cheerio.load(content);
            // let total_page = $('#pagination span').find('.isDefault').last().text()
            let total_page = 716
            for (let i = 1; i <= total_page; i++) {
                const url = `${this.root_url}${this.typeObj[type]}?isSel=true&page=${i}`
                await this.getPageData(url)
            }
        } catch (e) {
            console.log(e)
        }


    }
}

